//
//  YJQSportTypeModel.m
//  GoodLuck
//
//  Created by 杨瑞 on 16/12/12.
//  Copyright © 2016年 杨瑞. All rights reserved.
//

#import "YJQSportTypeModel.h"

/// GPS 信号变化通知
NSString *const YJQSportGPSSignalChangedNotification = @"YJQSportGPSSignalChangedNotification";

@implementation YJQSportTypeModel {
    CLLocation *_startLocation;
    /// 所有运动线条模型的数组
    NSMutableArray <YJQSportTrakingLineModel *>*_trackingLines;
    /// GPS 之前定位到的点
    CLLocation *_gpsPreLocation;
}

- (YJQSportGPSSignalState)gpsSignalWithLocation:(CLLocation *)location {
    YJQSportGPSSignalState state = YJQSportGPSSignalStateBad;
    // 1. 验证 speed 监测室内定位的情况 -1.00
    if (location.speed < 0) {
        [self postNotifyWithState:state];
        return state;
    }
    // 2. 判断是否有前一个记录点
    if (_gpsPreLocation == nil) {
        _gpsPreLocation = location;
        [self postNotifyWithState:state];
        return state;
    }
    // 测试两个定位点之间的时间差值
    NSTimeInterval delta = ABS([location.timestamp timeIntervalSinceDate:_gpsPreLocation.timestamp]);
    delta = ABS(delta - 1);
    if (delta < 0.01) {
        state = YJQSportGPSSignalStateGood;
    }else if (delta < 1) {
        state = YJQSportGPSSignalStateNormal;
    }
    [self postNotifyWithState:state];
    // 3. 记录之前的点
    _gpsPreLocation = location;
    return state;
}

/**
 发送 GPS 信号强度枚举通知
 
 @param state GPS 信号强度枚举
 */
- (void)postNotifyWithState:(YJQSportGPSSignalState)state {
    [[NSNotificationCenter defaultCenter] postNotificationName:YJQSportGPSSignalChangedNotification object:@(state)];
}

- (instancetype)initWithSportType:(YJQSportType)sportType state:(YJQSportState)state
{
    self = [super init];
    if (self) {
        _sportType = sportType;
        _state = state;
        _trackingLines = [NSMutableArray array];
    }
    return self;
}
#pragma mark - 设置数据
-(void)setState:(YJQSportState)state {
    _state = state;
    //判断运动状态类型，如果不是继续，需要清空起始点（防止暂停之后 再继续 会出现暂停点和再继续点直线连接）
    if (_state != YJQSportStateContinue) {
        _startLocation = nil;
    }
}
-(UIImage *)image {
    UIImage *image;
    switch (_sportType) {
        case YJQSportTypeWalk:
            image = [UIImage imageNamed:@"map_annotation_walk"];
            break;
        case YJQSportTypeRun:
            image = [UIImage imageNamed:@"map_annotation_run"];
            break;
        case YJQSportTypeRide:
            image = [UIImage imageNamed:@"map_annotation_bike"];
            break;
    }
    return image;
}
/**
 根据参数location`修改`用户的运动状态
 
 @param location location
 */
- (void)checkSportStateWithLocation:(CLLocation *)location {
    if (self.sportStartLocation == nil) {
        return;
    }
    if (location.speed == 0 && _state == YJQSportStateContinue) {
        _state = YJQSportStatePause;
        NSLog(@"运动状态切换为 -> 暂停");
    }
    if (location.speed > 0 && _state == YJQSportStatePause) {
        _state = YJQSportStateContinue;
        NSLog(@"运动状态切换为 -> 继续");
    }
}


-(YJQSportPolyline *)appendLocation:(CLLocation *)location {
    // 1. 判断 GPS 信号
    if ([self gpsSignalWithLocation:location] < YJQSportGPSSignalStateNormal) {
        return nil;
    }
    [self checkSportStateWithLocation:location];
    if (_state != YJQSportStateContinue) {
        return nil;
    }
//    //判断运动速度是否发生变化
//    if (location.speed <= 0) {
//        return nil;
//    }
//    //判断定位的时间差值
//    CGFloat factor = 2;
//    if ([[NSDate date] timeIntervalSinceDate:location.timestamp] > factor) {
//        //如果定位的时间超过，就不绘制轨迹
//        return nil;
//    }
    if (!_startLocation) {
        _startLocation = location;
        return nil;
    }
    //测试数据
    NSLog(@"%f - %f - %f - %f",self.avgSpeed,self.maxSpeed,self.totleTime,self.totleDistance);
    //创建追踪线条模型
    YJQSportTrakingLineModel *trakingLine = [[YJQSportTrakingLineModel alloc]initWithStartLocation:_startLocation endLocation:location];
    [_trackingLines addObject:trakingLine];
    _startLocation = location;
    return trakingLine.polyline;
}
-(double)avgSpeed {
    return [[_trackingLines valueForKeyPath:@"@avg.speed"] doubleValue];
}
-(double)maxSpeed {
    return [[_trackingLines valueForKeyPath:@"@max.speed"] doubleValue];
}
-(double)totleTime {
    return [[_trackingLines valueForKeyPath:@"@sum.time"] doubleValue];
}
-(double)totleDistance {
    return [[_trackingLines valueForKeyPath:@"@sum.distance"] doubleValue];
}
-(NSString *)totalTimes {
    NSInteger totalTime = (NSInteger)self.totleTime;
    return [NSString stringWithFormat:@"%02zd:%02zd:%02zd",totalTime / 3600,(totalTime % 3600) / 60,totalTime % 60];
}
-(CLLocation *)sportStartLocation {
    return _trackingLines.firstObject.startLocation;
}
@end
